package com.jyt.motor.service.impl;

import com.jyt.motor.service.AlarmLampService;
import com.jyt.motor.util.AlarmClass;
import com.jyt.motor.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.Semaphore;

@Service
public class AlarmLampServiceImpSerialPort implements AlarmLampService {

    Semaphore semaphore = null;
    AlarmClass ac = null;

    @Value("${motor.alarmCOM}")
    private String alarmCOM;

    private Integer sleepMilliSeconds = 80;
    Object lockObj = new Object();

    private boolean init() {
        //首次初始化
        if (semaphore == null) {
            synchronized (lockObj) {
                if (semaphore == null) {
                    semaphore = new Semaphore(1);
                    ac = new AlarmClass();
                    //
                    ac.selectPort(alarmCOM);
                }
            }
        }
        //如果端口打开未打开或打开失败，打开
        if (!ac.isPortOpen()) {
            synchronized (lockObj) {
                if (!ac.isPortOpen()) {
                    ac.selectPort(alarmCOM);
                }
            }
        }
        return ac.isPortOpen();
    }

    public void setPortName() {
        ac.selectPort(alarmCOM);
    }

    public void setPortName(String portName) {
        ac.selectPort(portName);
    }

    public void closePort() {
        ac.close();
    }

    @Override
    public void openAlarmLamp() {
        if(StringUtils.isBlank(alarmCOM))
        {
            return;
        }
        init();
        try {
            semaphore.acquire();
            //ac.selectPort(alarmSerialPort);
            byte[] message = {(byte) 0x01, (byte) 0x05, 0x00, 0x00, (byte) 0xFF, 0x00, (byte) 0x8C, (byte) 0x3A};
            ac.write(message);
            Thread.sleep(sleepMilliSeconds);
            //ac.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }

    @Override
    public void closeAlarmLamp() {
        if(StringUtils.isBlank(alarmCOM))
        {
            return;
        }
        init();
        try {
            semaphore.acquire();
            //ac.selectPort(alarmSerialPort);
            byte[] message = {(byte) 0x01, (byte) 0x05, 0x00, 0x00, 0x00, 0x00, (byte) 0xCD, (byte) 0xCA};
            ac.write(message);
            Thread.sleep(sleepMilliSeconds);
            //ac.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }
}
